package com.example.qqfake;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class FriendActivity extends AppCompatActivity implements OnItemButtonClickListener{
    private final String serverAddress = "192.168.104.215";
    private final int serverPort = 50000;

    public Socket socket;
    private BufferedReader in;
    private PrintWriter out;

    RecyclerView mRecyclerView;
    private MyAdapter adapter;
    private ImageView xiaoxi;
    private ImageView geren;
    private  AlertDialog.Builder builder1;
    private String new_user_id;
    private String new_user_name;

    //好友list
    List<User> mContactsList = new ArrayList<>();


    private String currentUserId; // 当前登录用户ID

    private int friend_count=0;

    @SuppressLint("NotifyDataSetChanged")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friends);
        // 获取SharedPreferences实例，文件名为"myPreferences"，与MainActivity中使用的文件名相同
        SharedPreferences sharedPreferences = getSharedPreferences("myPreferences", Context.MODE_PRIVATE);
        // 读取数据，键为"User_id"
        currentUserId = sharedPreferences.getString("User_id","hhh");
        mRecyclerView = findViewById(R.id.recyclerview);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);

        mRecyclerView.setLayoutManager(linearLayoutManager);

        adapter = new MyAdapter(mContactsList,this);
        mRecyclerView.setAdapter(adapter);

        xiaoxi = findViewById(R.id.chat);
        xiaoxi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(FriendActivity.this, MainActivity.class);
                startActivity(intent);
                FriendActivity.this.finish();
            }
        });
        geren = findViewById(R.id.myhome);
        geren.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(FriendActivity.this, EditProfileActivity.class);
                startActivity(intent);
                FriendActivity.this.finish();

            }
        });
        // 创建一个AlertDialog的构建器
        builder1 = new AlertDialog.Builder(this);


        //子线程开启socket发送连接请求，不停监听信息
        new Thread(()->{
            try {
                mContactsList.clear(); // 清空当前联系人列表

                socket= new Socket(serverAddress, serverPort);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out= new PrintWriter(socket.getOutputStream(), true);


                Date now = new Date();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String formattedString = formatter.format(now);

                //获取所有好友的信息
                String message1 = "7,"+currentUserId+","+formattedString+","+currentUserId+","+currentUserId;
                out.println(message1);

                // 启动读取消息的线程
                new Thread(this::readMessages).start();
                /*
                 * 由FriendActivity发送的消息：
                 *
                 * 2.删除好友消息，返回false4代表删除失败，弹窗提示已经删除
                 *              返回true代表删除成功，弹窗提示删除成功
                 * 3.查找所有好友的请求，返回好友信息
                 * */

            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }).start();

//更新适配器的数据源
        adapter.setData(mContactsList); // 更新适配器的数据
        adapter.notifyDataSetChanged();


    // 初始化SearchView和SearchButton
        //EditText searchView = findViewById(R.id.searchView);
        findViewById(R.id.searchButton).setOnClickListener(v -> {
            Intent intent1 = new Intent(FriendActivity.this,FindresultActivity.class);
            intent1.putExtra("id",currentUserId);
            startActivity(intent1);
            System.exit(0);
        });





    }
    @Override
    public void onItemButton2Click(int position) {
        String id = Integer.toString(mContactsList.get(position).getId());
        // 在这里处理第二个按钮的点击事件
        deleteAContact(id);
    }


    //删除联系人
    private void deleteAContact(String user_id){
        //子线程发送消息
        Date now = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedString = formatter.format(now);
        String message = "5,"+currentUserId+","+formattedString+","+currentUserId+" "+user_id+","+currentUserId;

        Thread thread = new Thread(new Worker(message));
        thread.start();



    }





    @SuppressLint("NotifyDataSetChanged")
    private void readMessages() {
        try {
            String message;
            while ((message = in.readLine()) != null) {
                if(message.equals("false6")){
                    break;
                }
               else if(message.contains("@")){
                    //删除好友成功，返回删除好友的信息
                    String[] ziduan=message.split("@");
                    if(!isFinishing()){
                        runOnUiThread(new Runnable() {//此run方法将由主线程运行
                            @SuppressLint("NotifyDataSetChanged")
                            @Override
                            public void run() {
                                friend_count--;
                                User delete_user =new User(Integer.parseInt(ziduan[0]),ziduan[1]);
                                Toast.makeText(FriendActivity.this, "删除联系人成功", Toast.LENGTH_SHORT).show();
                                //刷新联系人列表
                                mContactsList.remove(delete_user);
                                adapter.setData(mContactsList); // 更新适配器的数据
                                adapter.notifyDataSetChanged();

                            }
                        });
                    }
                    break;
                }else{
                    String[] data = message.split(" ");
                    User user = new User(Integer.parseInt(data[0]),data[1]);
                    if(!isFinishing()){
                       runOnUiThread(new Runnable() {//此run方法将由主线程运行
                           @SuppressLint("NotifyDataSetChanged")
                           @Override
                           public void run() {
                               //更新适配器的数据源
                               adapter.addItem(user);
                           }
                       });
                   }
                }



            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public class Worker implements Runnable {
        private String message;
        public Worker(String message) {
            this.message = message;
        }
        @Override
        public void run() {
            // 使用传递的消息
            out.println(message);
        }
    }


    @Override
    public void onDestroy() {

        super.onDestroy();
        try{
            //关闭输入流，socket连接
            if(socket!=null){
                socket.close();

            }
        }catch(IOException e){
            e.printStackTrace();

        }

    }

}
